import React, { useState } from 'react';
import axios from 'axios';
import './Home.css';

const Home = () => {
  const [selectedFile, setSelectedFile] = useState(null);
  const [previewImage, setPreviewImage] = useState(null);
  const [processedImage, setProcessedImage] = useState(null);
  const [operation, setOperation] = useState('rotate');
  const [parameter, setParameter] = useState('');
  const [imageSize, setImageSize] = useState({ width: 0, height: 0 });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  
  const handleFileChange = (event) => {
    const file = event.target.files[0];
    if (file) {
      setSelectedFile(file);
      setPreviewImage(URL.createObjectURL(file));
      setError(null);
    }
  };

  const handleOperationChange = (event) => {
    setOperation(event.target.value);
    setParameter('');
  };

  const handleParameterChange = (event) => {
    setParameter(event.target.value);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    if (!selectedFile) {
      setError('请选择一张图像');
      return;
    }

    setLoading(true);
    setError(null);
    const formData = new FormData();
    formData.append('file', selectedFile);
    formData.append('operation', operation);
    formData.append('parameter', parameter);

    try {
      const response = await axios.post('http://localhost:5000/process-image', formData, {
        responseType: 'blob',
      });

      const imageUrl = URL.createObjectURL(new Blob([response.data]));
      setProcessedImage(imageUrl);

      const img = new Image();
      img.onload = () => {
        setImageSize({ width: img.width, height: img.height });
      };
      img.src = imageUrl;
    } catch (error) {
      setError('处理图像时发生错误，请重试');
      console.error('Error processing image:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    setSelectedFile(null);
    setPreviewImage(null);
    setProcessedImage(null);
    setOperation('rotate');
    setParameter('');
    setError(null);
  };

  const renderParameterInput = () => {
    switch (operation) {
      case 'rotate':
        return (
          <div className="parameter-input">
            <label htmlFor="rotate-degree">旋转度数</label>
            <input
              id="rotate-degree"
              type="number"
              value={parameter}
              onChange={handleParameterChange}
              placeholder="输入旋转角度（0-360）"
            />
          </div>
        );
      case 'scale':
        return (
          <div className="parameter-input">
            <label htmlFor="scale-factor">缩放倍数</label>
            <input
              id="scale-factor"
              type="number"
              step="0.1"
              value={parameter}
              onChange={handleParameterChange}
              placeholder="输入缩放倍数（如：1.5）"
            />
          </div>
        );
      case 'filter':
        return (
          <div className="parameter-input">
            <label htmlFor="filter-type">滤镜类型</label>
            <select
              id="filter-type"
              value={parameter}
              onChange={handleParameterChange}
            >
              <option value="">请选择滤镜</option>
              <option value="BLUR">模糊</option>
              <option value="EMBOSS">浮雕</option>
              <option value="CONTOUR">轮廓</option>
              <option value="SHARPEN">锐化</option>
            </select>
          </div>
        );
      case 'color_adjust':
        return (
          <div className="color-adjust-inputs">
            <div className="parameter-input">
              <label htmlFor="r-channel">R通道调整</label>
              <input
                id="r-channel"
                type="number"
                step="0.1"
                value={parameter.split(',')[0] || ''}
                onChange={(e) => handleParameterChange({ target: { value: `${e.target.value},${parameter.split(',')[1] || ''},${parameter.split(',')[2] || ''}` } })}
                placeholder="R通道（0-2）"
              />
            </div>
            <div className="parameter-input">
              <label htmlFor="g-channel">G通道调整</label>
              <input
                id="g-channel"
                type="number"
                step="0.1"
                value={parameter.split(',')[1] || ''}
                onChange={(e) => handleParameterChange({ target: { value: `${parameter.split(',')[0] || ''},${e.target.value},${parameter.split(',')[2] || ''}` } })}
                placeholder="G通道（0-2）"
              />
            </div>
            <div className="parameter-input">
              <label htmlFor="b-channel">B通道调整</label>
              <input
                id="b-channel"
                type="number"
                step="0.1"
                value={parameter.split(',')[2] || ''}
                onChange={(e) => handleParameterChange({ target: { value: `${parameter.split(',')[0] || ''},${parameter.split(',')[1] || ''},${e.target.value}` } })}
                placeholder="B通道（0-2）"
              />
            </div>
          </div>
        );
      default:
        return null;
    }
  };

  return (
    <div className="home-container">
      <div className="home-content">
        <h1 className="title">基础图像处理</h1>
        <p className="subtitle">
          上传一张图像，选择处理操作，我们将为您生成处理后的图像
        </p>

        {error && (
          <div className="error-message">
            {error}
          </div>
        )}

        <form onSubmit={handleSubmit}>
          <div className="image-upload-section">
            <h2>选择图像</h2>
            <label className="upload-button">
              <span>选择图像</span>
              <input
                type="file"
                accept="image/*"
                onChange={handleFileChange}
              />
            </label>
            
            {previewImage && (
              <div className="image-preview">
                <h3>原图预览</h3>
                <img src={previewImage} alt="预览" />
              </div>
            )}
          </div>
          
          <div className="operation-section">
            <h2>选择操作</h2>
            <div className="operation-selector">
              <select 
                value={operation} 
                onChange={handleOperationChange}
                className="operation-select"
              >
                <option value="rotate">旋转</option>
                <option value="flip">翻转</option>
                <option value="scale">缩放</option>
                <option value="filter">加滤镜</option>
                <option value="color_adjust">调整颜色</option>
                <option value="contrast">对比度增强</option>
                <option value="smooth">图像平滑处理</option>
              </select>
            </div>
            
            <div className="parameter-section">
              <h3>参数设置</h3>
              {renderParameterInput()}
            </div>
          </div>
          
          <div className="button-group">
            <button
              type="submit"
              className="submit-button"
              disabled={loading || !selectedFile}
            >
              {loading ? '处理中...' : '处理图像'}
            </button>
            <button
              type="button"
              className="reset-button"
              onClick={handleReset}
            >
              重置
            </button>
          </div>
        </form>
        
        {processedImage && (
          <div className="result-section">
            <h2>处理后的图像</h2>
            <div className="result-image-container">
              <img 
                src={processedImage} 
                alt="处理后的图像" 
                width={imageSize.width} 
                height={imageSize.height}
              />
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default Home;
